<template>
  <div class="main_center">
    <div class="menu_select">
      <div class="data_list">
        <div class="select_item">
          <span class="demonstration">开始时间 </span>
          <el-date-picker   v-selfdbclick  v-model="localStartDate" type="datetime" placeholder="选择开始日期">
          </el-date-picker>
        </div>

      </div>
      <div class="data_list">
        <div class="select_item">
          <span class="demonstration">结束时间 </span>
          <el-date-picker   v-selfdbclick  v-model="localEndDate" type="datetime" placeholder="选择结束日期">
          </el-date-picker>
        </div>

      </div>
      <div class="data_list">
        <div class="select_item">
          <span class="demonstration">产品名称 </span>
          <el-select v-model="localProductName" @change="handleProductNameChange">
            <el-option v-for="item in productNames" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </div>

      </div>
      <div class="data_list">
        <div class="select_item">
          <span class="demonstration">物料颜色 </span>
          <el-select v-model="localColor">
            <el-option v-for="item in localProductColors" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </div>
      </div>

      <!-- <div class="data_list">
        <div class="select_item">
          <span class="demonstration">SN: </span>
          <el-input v-model="queryMain.qrCode"></el-input>
        </div>

      </div> -->
      <div class="data_list" style="flex:3">
        <div class="btn_list">
          <!-- <div class="btn" @click="search">查询</div>
          <div class="btn_export" style="margin-left: 15px;" @click="callParentMethodExportData">导出数据</div> -->
          <el-button type="primary" @click="search">查询</el-button>
          <el-button type="primary" @click="callParentMethodExportData">导出数据</el-button>
        </div>

      </div>
    </div>
    <div class="main_checkbox">
      <div class="left-content">
        <el-radio v-model="queryMain.productOrDefect" label="product" @change="selectType('product')" v-if="productQuality">按产品数
        </el-radio>
        <el-radio v-model="queryMain.productOrDefect" label="defect" @change="selectType('defect')" v-if="productQuality">按缺陷数</el-radio>
        <el-select
            v-model="selectDefectCategory"
            multiple
            collapse-tags
            style="margin-left: 20px; width: 300px"
            placeholder="请选择缺陷类别"
            v-if="productQuality"
            @visible-change="handleSelectVisibilityChange"
            @remove-tag="handleTagRemove"
        >
          <el-option
              v-for="item in defectCategorys"
              :key="item"
              :label="item"
              :value="item">
          </el-option>
        </el-select>
      </div>

      <div class="right-content">
        <el-switch
            style="display: block"
            v-model="productQuality"
            active-color="#F061E7"
            inactive-color="#0F62FE"
            active-text="缺陷"
            inactive-text="产能/良率"
            @change="handleSwitchChange"
        >
        </el-switch>
      </div>
    </div>
    <div class="main_content item_content content_echart">
      <div class="charts" style="width: 100%; height: 100%;">
        <div ref="chartOverview" class="chart extra-small-chart"></div>
        <div ref="chartDaily" class="chart large-chart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {formatDate} from "../../utils/tools";


export default {
  name: 'DataAnalysis',
  inheritAttrs: false,
  data() {
    return {
      localStartDate: this.startDate ? new Date(this.startDate) : null,
      localEndDate: this.endDate ? new Date(this.endDate) : null,
      localColor: this.color,
      localProductColors: this.productColors,
      localProductName: this.productName,
      isLocalUpdate: false,
      dataAnalysisQrCode: '',
      queryMain: {
        type: 4,
        startTime: "",
        endTime: "",
        color: "全部", // 产品颜色 默认全部
        productName: "全部", // 产品名称，默认全部
        productOrDefect: "product", // 按照产品或缺陷，默认按产品
        qrCode: "", // sn码，不输入默认为空，则忽略不过滤
        mode: 1,
        types: []
      },
      chartTotalNameOverview: [], // 示例名称，表示两个总数叠加
      chartTotalDataOverview: [], // 示例数据，表示两个总数叠加
      chartSingleNameOverview: [], // 示例名称，表示单个总数

      chartTotalSeries: [

      ],
      chartSingleSeries: [],
      totalLineData: [],  // 总计示例折线数据
      lineData: [],  // 示例折线数据
      chartTotalCategoriesDaily: [],
      chartCategoriesDaily: [], // 31天

      chartTotalInstance: null,
      chartSingleInstance: null,

      productQuality: false,
      selectDefectCategory: "",
      defectCategorys: [],
      fixedColors: [
        '#0F62FE', '#6BB2FB', '#F061E7', '#FFDA2E', '#8A3BEF',
        '#09DA97', '#6884FF', '#FFA495', '#87D46A', '#6699FF'
      ]
    }
  },
  props: {
    qtCall: {
      type: Object,
      default: null
    },
    startDate: {
      type: [Date, String],
      default: null
    },
    endDate: {
      type: [Date, String],
      default: null
    },
    color: {
      type: String,
      default: '全部'
    },
    productName: {
      type: String,
      default: '全部'
    },
    exportData: {
      type: Function,
      required: true
    },
    productNames: {
      type: Array,
      default: () => ["全部"]
    },
    productColors: {
      type: Array,
      default: () => ["全部"]
    },
    allColor: {
      type: Array,
      default: () => ["全部"]
    },
    productNameAndColor: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    formattedLocalStartDate: {
      get() {
        return this.localStartDate ? this.localStartDate.toISOString() : null;
      },
      set(value) {
        this.localStartDate = value ? new Date(value) : null;
      }
    },
    formattedLocalEndDate: {
      get() {
        return this.localEndDate ? this.localEndDate.toISOString() : null;
      },
      set(value) {
        this.localEndDate = value ? new Date(value) : null;
      }
    },

  },
  watch: {
    startDate(newVal) {
      if (!this.isLocalUpdate) {
        this.localStartDate = newVal ? new Date(newVal) : null;
      }
      this.isLocalUpdate = false;
    },
    endDate(newVal) {
      if (!this.isLocalUpdate) {
        this.localEndDate = newVal ? new Date(newVal) : null;
      }
      this.isLocalUpdate = false;
    },
    color(newVal) {
      this.localColor = newVal;
    },
    localStartDate(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.isLocalUpdate = true;
        this.$emit('update:startDate', newVal ? newVal.toISOString() : null);
      }
    },
    localEndDate(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.isLocalUpdate = true;
        this.$emit('update:endDate', newVal ? newVal.toISOString() : null);
      }
    },
    localColor(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.$emit('update:color', newVal);
      }
    },
    localProductName(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.$emit('update:productName', newVal);
      }
    }
  },
  mounted() {
      // 打印传递过来的 props 数据
    setTimeout(() => {
      if (this.startDate && this.endDate){
        this.search();
      }
      this.initChartOverview();
      this.initChartDaily();
    }, 100)
  },
  methods: {
    selectType(type_value) {
      this.queryMain.productOrDefect = type_value;
      if(this.localStartDate && this.localEndDate){
        this.search();
      }
    },
    search() {
      console.log("search");
      if (!this.localStartDate) {
        this.$message.error("请选择起始时间");
        return;
      }
      if (!this.localEndDate) {
        this.$message.error("请选择结束时间");
        return;
      }
      if (this.localStartDate > this.localEndDate) {
        this.$message.error('开始时间不能大于结束时间')
        return;
      }
      const startTime = formatDate(this.localStartDate);
      const endTime = formatDate(this.localEndDate);
      if (process.env.NODE_ENV === 'production') {
        if (this.queryMain.mode === 2 && (this.queryMain.startTime !== startTime || this.queryMain.endTime !== endTime)) {
          this.handleSwitchChange(true);
        }
      }
      this.queryMain.startTime = startTime;
      this.queryMain.endTime = endTime;
      if (this.localColor === '') {
        this.queryMain.color = '全部'
      } else {
        this.queryMain.color = this.localColor
      }
      if (this.localProductName === '') {
        this.queryMain.productName = '全部'
      } else {
        this.queryMain.productName = this.localProductName
      }
      if (process.env.NODE_ENV === 'production') {
        console.log('数据分析’，传参' , this.queryMain)
        this.qtCall.QtToJs.connect((func, json) => {
          if (func === "RefreshHistoryInDataAnalysisQualityAnalysis") {
            const datas = JSON.parse(json)
            if (datas.code === 200) {
              console.log('数据分析’，接口返回RefreshHistoryInDataAnalysisQualityAnalysis' , datas.data)
              const result = JSON.parse(datas.data.data);
              // if (this.chartTotalInstance){
              //   this.chartTotalInstance.dispose();
              //   this.chartTotalInstance = null;
              // }
              // if (this.chartSingleInstance) {
              //   this.chartSingleInstance.dispose();
              //   this.chartSingleInstance = null;
              // }
              this.chartTotalNameOverview = [];
              this.chartTotalDataOverview = [];
              this.chartSingleNameOverview = [];
              this.chartTotalSeries = [];
              this.chartSingleSeries = [];
              this.totalLineData = [];
              this.lineData = [];
              this.chartCategoriesDaily = [];
              this.chartTotalCategoriesDaily = [];

              this.initChartOverview();
              this.initChartDaily();
              console.log("打印柱状图的数据（string）：", datas.data.data)
              if (result.barData.length === 0 ) {
                this.$message.closeAll();
                this.$message.warning("没有查询到数据");
                return ;
              }
              console.log("打印柱状图的数据：", JSON.parse(datas.data.data))
              this.handleQtData(JSON.parse(datas.data.data));
            }
          }
        })
        this.qtCall.JsToQt("NeedQueryHistoryInQualityAnalysis", this.queryMain);//可以传给qt
      } else {
        // const d = "{\"barData\":[{\"name\": \"图例1\",\"color\": \"#3398DB\",\"total\": 100,\"data\": [38,2,3,4,386,56,6,77,9]},{\"name\": \"图例2\",\"color\": \"#d14a61\",\"total\": 200,\"data\": [10,2,3,4,11,56,6,77,9]}],\"BrokenLineData\": [0.00756756,0.00342343,0.0047567,0.00405,0.0057],\"x-axis\": [\"2024-07-01\",\"2024-07-02\",\"2024-07-03\",\"2024-07-04\",\"2024-07-05\",\"2024-07-06\",\"2024-07-07\",\"2024-07-08\",\"2024-07-09\"]}"
        // const d= "{\"BrokenLineData\":[],\"barData\":[{\"color\":\"#46CBB3\",\"data\":[469],\"name\":\"小A面三伤\",\"total\":469},{\"color\":\"#369FB3\",\"data\":[794],\"name\":\"装饰件侧壁三伤\",\"total\":794},{\"color\":\"#39C359\",\"data\":[283],\"name\":\"装饰件侧壁溢胶\",\"total\":283},{\"color\":\"#5AE54B\",\"data\":[672],\"name\":\"装饰环三伤\",\"total\":672}],\"x-axis\":[\"20240803\",\"20240804\",\"20240806\",\"20240807\",\"20240810\",\"20240812\",\"20240813\",\"20240814\"]}"

        // const d = "{\"BrokenLineData\":[],\"barData\":[{\"color\":\"#46CBB3\",\"data\":[469],\"name\":\"小A面三伤\",\"total\":469},{\"color\":\"#369FB3\",\"data\":[794],\"name\":\"装饰件侧壁三伤\",\"total\":794},{\"color\":\"#39C359\",\"data\":[283],\"name\":\"装饰件侧壁溢胶\",\"total\":283},{\"color\":\"#5AE54B\",\"data\":[672],\"name\":\"装饰环三伤\",\"total\":672}],\"x-axis\":[\"20240803\"]}"
        // this.handleQtData(JSON.parse(d));

        const e = {
          "BrokenLineData":[
            {"color":"#46CBB3","data":[80.0201,234.0201,125.0201],"name":"Test_2","total":31.477},
            {"color":"#369FB3","data":[51.0201,345.0201,21.0201],"name":"Test_5","total":34.77},
            {"color":"#39C359","data":[8.0201,225.0201,188.0201],"name":"Test_6","total":35.77}
          ],
          "barData":[
            {"color":"#46CBB3","data":[81,2325,13],"name":"Test_2","total":31477},
            {"color":"#369FB3","data":[51,235,143],"name":"Test_5","total":31477},
            {"color":"#39C359","data":[851,225,124],"name":"Test_6","total":31477}
          ],
          "x-axis":["20240813","20240814","20240815"]
        }
        //
        // const e = {
        //   "BrokenLineData":[
        //     {"data":[0,4.2578558350214735e-05,0.05882352963089943],"name":"良率"}
        //   ],
        //   "barData":[
        //     {"color":"#46CBB3","data":[8051,23486,68],"name":"投产总数","total":31605}
        //   ],
        //   "x-axis":["20240813","20240814","20240815"]
        // }
        this.handleQtData(e);
        const datas = {
          "code": 200,
          "data": {
            "types": [
              "Test_9",
              "Test_8",
              "Test_7",
              "Test_6",
              "Test_5",
              "Test_4",
              "Test_3",
              "Test_2",
              "Test_1",
              "Test_0",
              "孔内壁不良",
              "装饰环侧壁溢胶",
              "装饰件侧壁三伤",
              "装饰环三伤",
              "镜片白点",
              "装饰件、环缺陷",
              "装饰环侧壁三伤",
              "小A面三伤",
              "板材三伤",
              "你不好",
              "装饰件侧壁溢胶",
              "CG大面缺陷",
              "装饰环溢胶/夹胶",
              "镜片异色",
              "漏工艺-大字符缺失",
              "边透光",
              "装饰件侧壁擦伤/压伤",
              "闪光灯不良",
              "辅料不良",
              "小A面擦伤",
              "孔内异色",
              "装饰环缺陷",
              "混环检测",
              "板材异色",
              "麦拉缺失",
              "装饰环压伤",
              "装饰环侧壁细划伤",
              "孔侧壁麻点",
              "闪光灯脏污/异色",
              "LOGO三伤",
              "装饰环侧壁擦伤/压伤",
              "背胶偏移",
              "孔侧壁异色",
              "板材崩边",
              "Other",
              "小A面细划伤",
              "背胶缺失",
              "CG三伤",
              "圆孔/方孔侧壁白点",
              "镜片三伤",
              "边透光/大背胶偏移",
              "镜面膜缺失",
              "泡棉缺失",
              "装饰件侧壁划伤",
              "漏工艺-混环",
              "装饰件溢胶/夹胶",
              "你好",
              "划伤",
              "装饰件侧壁细划伤",
              "装饰环划伤",
              "小A面硬划伤",
              "闪光孔膜缺失",
              "CG异色",
              "小LOGO缺陷",
              "板材擦伤/压伤",
              "麦拉偏移",
              "板材硬划伤",
              "镜片划伤",
              "防水标缺失",
              "圆孔/方孔侧壁脏污",
              "辅料缺失-顶部麦拉",
              "小A面压伤",
              "孔侧壁划伤",
              "镜片脏污",
              "镜片亮点",
              "辅料缺失-顶部小泡棉",
              "防水标发红",
              "板材细划伤"
            ]
          },
          "msg": ""
        }
        this.defectCategorys = datas.data.types;
      }
    },
    // 处理 QT 传递过来的数据
    handleQtData(datas) {
      if (!this.chartTotalInstance) {
        this.chartTotalInstance = echarts.init(this.$refs.chartOverview);
      }
      if (!this.chartSingleInstance) {
        this.chartSingleInstance = echarts.init(this.$refs.chartDaily);
      }
      this.chartTotalNameOverview = datas.barData && datas.barData.length > 0
        ? datas.barData.map(item => item.name)
        : [];
      this.chartTotalDataOverview = datas.barData && datas.barData.length > 0
        ? datas.barData.map(item => item.name)
        : [];

      // this.chartSingleNameOverview = datas.BrokenLineData.length !== 0
      //   ? this.chartTotalNameOverview.concat('良率')
      //   : this.chartTotalNameOverview;

      this.chartTotalSeries = datas.barData && datas.barData.length > 0
        ? datas.barData.map(item => {
          return {
            name: item.name,
            type: 'bar',
            stack: 'total',
            barWidth: 50,
            data: [item.total], // 这里使用 item.total 的数组形式
            color: item.color
          };
        })
        : [];
      this.totalLineData = datas.BrokenLineData && datas.BrokenLineData.length > 0
        ? datas.BrokenLineData.map(item => {
          return {
            name: item.name,
            type: 'line',
            data: [parseFloat(item.total).toFixed(2)],
          };
        })
        : [];

      this.chartSingleSeries = datas.barData && datas.barData.length > 0
        ? datas.barData.map(item => {
          return {
            name: item.name,
            type: 'bar',
            stack: 'total',
            barWidth: 30,
            data: item.data,
            color: item.color
          };
        })
        : [];

      this.lineData = datas.BrokenLineData && datas.BrokenLineData.length > 0
        ? datas.BrokenLineData.map(item => {
          return {
            name: item.name,
            type: 'line',
            data: item.data.map(dataItem => parseFloat(dataItem).toFixed(2)), // 确保数据是数值类型并保留两位小数
          };
        })
        : [];

      this.chartCategoriesDaily = datas['x-axis'];
      this.chartTotalCategoriesDaily = ['总计'];

      this.initChartOverview();
      this.initChartDaily();
    },
    initChartOverview() {
      if (!this.chartTotalInstance) {
        this.chartTotalInstance = echarts.init(this.$refs.chartOverview);
      }
      let left_name = "投产数"
      let right_name = "良率"
      if (this.productQuality) {
        left_name = "缺陷数量"
        right_name = "不良率"
      }
      const option = {
        title: {
          text: '总计',
          top: '0', // 调整标题的位置
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {type: 'shadow'},
          position: function (point, params, dom, rect, size) {
            const x = point[0] + 20; // 向右偏移 20 像素
            const y = point[1] - 120; // 向上偏移 20 像素
            return [x, y];
          },
          formatter: params => {
            // 提取公共的时间轴标签
            const axisLabel = params[0].name;
            // 处理 tooltip 显示内容
            let total_num = 0;
            // 用于存储同名的 series 数据
            const seriesDataMap = {};
            // 将数据按 seriesName 进行归类
            params.forEach(item => {
              if (!seriesDataMap[item.seriesName]) {
                seriesDataMap[item.seriesName] = {
                  lineValue: null,
                  barValue: null
                };
              }
              if (item.seriesType === 'line') {
                seriesDataMap[item.seriesName].lineValue = item.value;
              } else {
                seriesDataMap[item.seriesName].barValue = item.value;
                total_num += item.value;
              }
            });
            // 生成 tooltip 内容
            const tooltipContent = Object.keys(seriesDataMap).map(seriesName => {
              const marker = params.find(item => item.seriesName === seriesName).marker;
              const lineValue = seriesDataMap[seriesName].lineValue !== null
                ? `${seriesDataMap[seriesName].lineValue}%`
                : null;
              const barValue = seriesDataMap[seriesName].barValue !== null
                ? `${seriesDataMap[seriesName].barValue}`
                : null;

              let valueDisplay = '';
              if (lineValue && barValue) {
                valueDisplay = `${lineValue}（${barValue}）`;
              } else if (lineValue) {
                valueDisplay = `${lineValue}`;
              } else if (barValue) {
                valueDisplay = `${barValue}`;
              }

              return `${marker}${seriesName}: &nbsp;&nbsp;&nbsp;<strong>${valueDisplay}</strong>`;
            }).join('<br/>');

            const totalLine = `<br/><br/><strong>总和: &nbsp;&nbsp;&nbsp;</strong><strong>${total_num}</strong>`;
            return `${axisLabel}<br/><br/>${tooltipContent}${totalLine}`;
          },
        },
        legend: {
          type: 'scroll',
          top: '5%', // 将图例放在标题下方
          left: 'center',
          data: this.chartTotalNameOverview,
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.chartTotalCategoriesDaily,
            axisTick: {alignWithLabel: true}
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '数量',
            position: 'left'
          },
          {
            type: 'value',
            name: right_name,
            position: 'right',
            axisLabel: {
              formatter: function (value) {
                return value + '%';
              },
            },
          }
        ],
        series: [
          ...this.chartTotalSeries.map((seriesItem, index) => ({
            ...seriesItem,
            label: {
              show: true,
              position: 'inside',
              formatter: '{c}', // {c} 会被替换为数据值
            },
            itemStyle: {
              color: this.fixedColors[index % this.fixedColors.length] // 使用不同的颜色
            }
            ,tooltip: {
              valueFormatter: function (value) {//内容格式器
                return value + ' 次';
              }
            },
          })),
          ...this.totalLineData.map((seriesItem, index) => ({
            ...seriesItem,
            yAxisIndex: 1,
            label: {
              show: true,
              position: 'top',
              formatter: params => {
                return `${params.value}%`;
              }
            },
            itemStyle: {
              color: this.fixedColors[index % this.fixedColors.length] // 使用不同的颜色
            },
            tooltip: {
              valueFormatter: function (value) {//内容格式器
                return value + ' 次';
              }
            },
          })),

        ]
      };
      this.chartTotalInstance.setOption(option, {notMerge: true});
    },
    initChartDaily: function () {
      if (!this.chartSingleInstance) {
        this.chartSingleInstance = echarts.init(this.$refs.chartDaily);
      }
      let left_name = "投产数"
      let right_name = "良率"
      if (this.productQuality) {
        left_name = "缺陷数量"
        right_name = "不良率"
      }
      const option = {
        title: {
          text: '每日数据',
          top: '0', // 调整标题的位置
          left: 'center'
        },
        tooltip: {
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => {
            const axisLabel = params[0].name;
            let total_num = 0;

            // 用于存储同名的 series 数据
            const seriesDataMap = {};

            // 将数据按 seriesName 进行归类
            params.forEach(item => {
              if (!seriesDataMap[item.seriesName]) {
                seriesDataMap[item.seriesName] = {
                  lineValue: null,
                  barValue: null
                };
              }
              if (item.seriesType === 'line') {
                seriesDataMap[item.seriesName].lineValue = item.value;
              } else {
                seriesDataMap[item.seriesName].barValue = item.value;
                total_num += item.value;
              }
            });

            // 生成 tooltip 内容
            const tooltipContent = Object.keys(seriesDataMap).map(seriesName => {
              const marker = params.find(item => item.seriesName === seriesName).marker;
              const lineValue = seriesDataMap[seriesName].lineValue !== null
                ? `${seriesDataMap[seriesName].lineValue}%`
                : null;
              const barValue = seriesDataMap[seriesName].barValue !== null
                ? `${seriesDataMap[seriesName].barValue}`
                : null;

              let valueDisplay = '';
              if (lineValue && barValue) {
                valueDisplay = `${lineValue}（${barValue}）`;
              } else if (lineValue) {
                valueDisplay = `${lineValue}`;
              } else if (barValue) {
                valueDisplay = `${barValue}`;
              }

              return `${marker}${seriesName}: &nbsp;&nbsp;&nbsp;<strong>${valueDisplay}</strong>`;
            }).join('<br/>');

            const totalLine = `<br/><br/><strong>总和: &nbsp;&nbsp;&nbsp;</strong><strong>${total_num}</strong>`;
            return `${axisLabel}<br/><br/>${tooltipContent}${totalLine}`;
          },
          trigger: 'axis'
        },
        legend: {
          type: 'scroll',
          top: '5%', // 将图例放在标题下方
          left: 'center',
          // data: this.chartSingleNameOverview
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '20%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.chartCategoriesDaily
        },
        yAxis: [
          {
            type: 'value',
            name: left_name,
            position: 'left'
          },
          {
            type: 'value',
            name: right_name,
            position: 'right',
            axisLabel: {
              formatter: function(value) {
                return value + '%';
              }
            }
          }
        ],
        series: [
          ...this.chartSingleSeries.map((seriesItem, index) => ({
            ...seriesItem,
            label: {
              show: true,
              position: 'inside',
              formatter: '{c}', // {c} 会被替换为数据值
            },
            itemStyle: {
              color: this.fixedColors[index % this.fixedColors.length] // 使用不同的颜色
            }
          })),
          ...this.lineData.map((seriesItem, index) => ({
            ...seriesItem,
            yAxisIndex: 1,
            label: {
              show: true,
              position: 'top',
              formatter: params => {
                return `${params.value}%`;
              }
            },
            itemStyle: {
              color: this.fixedColors[index % this.fixedColors.length] // 使用不同的颜色
            }
          })),
        ]
      };
      this.chartSingleInstance.setOption(option, { notMerge: true });
    },
    callParentMethodExportData() {
      this.queryMain.type = 4;
      this.queryMain.startTime = formatDate(this.localStartDate);
      this.queryMain.endTime = formatDate(this.localEndDate);
      this.exportData(this.queryMain);
    },
    handleSwitchChange(value) {
      if (value && this.localStartDate && this.localEndDate) {
        this.queryMain.startTime = formatDate(this.localStartDate);
        this.queryMain.endTime = formatDate(this.localEndDate);
        this.queryMain.mode = 2;
        this.selectDefectCategory = [];
        this.queryMain.types = [];
        if (process.env.NODE_ENV === 'production') {
          console.log('数据分析’，mode为 2 时，传参：' , this.queryMain)
          this.qtCall.JsToQt("NeedQueryHistoryTypesInQualityAnalysis", this.queryMain);
          this.qtCall.QtToJs.connect((func, json) => {
            if (func === "RefreshHistoryTypesInQualityAnalysis") {
              const datas = JSON.parse(json)
              if (datas.code === 200) {
                console.log('数据分析’，RefreshHistoryTypesInQualityAnalysis：' , datas.data)
                this.defectCategorys = datas.data.types;
              }
            }
          })
        }
      } else {
        this.queryMain.mode = 1;
        this.selectDefectCategory = [];
        this.queryMain.types = [];
      }
      this.search();
      this.initChartOverview();
      this.initChartDaily();
    },
    handleSelectVisibilityChange(isVisible) {
      if (this.selectDefectCategory.length > 5) {
        this.$message.closeAll();
        this.$message.warning("最多选择5个缺陷类别");
        return ;
      }
      if (!isVisible && this.selectDefectCategory !== this.queryMain.types) {
        console.log("触发筛选")
        this.queryMain.types = this.selectDefectCategory;
        this.search();
      }
    },
    handleProductNameChange(product_name) {
      console.log("product_name", product_name)
      console.log("this.allcolor", this.allColor)
      console.log("this.productNameAndColor", this.productNameAndColor)
      if (product_name === "全部") {
        this.localProductColors = this.allColor
        this.localColor = '全部'
      } else {
        console.log("this.localColor", this.productNameAndColor[product_name])
        this.localProductColors = [this.productNameAndColor[product_name]]
        this.localColor = this.productNameAndColor[product_name]
      }
    },
    handleTagRemove(tag) {
      console.log('删除了子项:', tag);
      this.handleSelectVisibilityChange(false);
    },
  }
}
</script>
<style scoped>
.main_bottom .main_right .main_center, .main_bottom .main_right .main_center .main_item {
  display: flex;
  width: calc(100% - 5px);
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  flex-direction: column;
}

.main_bottom .main_right .main_center {
  height: calc(100% + 4px);
}

.main_bottom .main_right .main_content {
  margin-top: -18px;
  padding: 0 0 1px 1px;
  width: calc(100% - 1px);
  height: calc(87% + 14px);
}

.charts {
  margin-top: 20px;
  padding: 10px;
  background-color: #FFFFFF;
  display: flex;
  justify-content: space-around;
  align-items: flex-start;
  box-shadow: 10px 10px 20px rgba(0, 0, 0, 0);
  width:100%;
  margin-left: 0px;
  padding-top: 20px;
  box-sizing: border-box;
}

.extra-small-chart {
  width: 25%;
  height:calc(100vh - 340px);
}

.large-chart {
  width: 70%;
  height:calc(100vh - 340px);
}

.main_checkbox {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-content {
  display: flex;
  align-items: center;
}

.right-content {
  display: flex;
  align-items: center;
  padding-right: 32px;
}
</style>
